<!-- 组件模型 -->
<script lang="ts" setup>
import type { ModelData, ModelSearchData } from "@@/apis/component/type.ts"
import type { FormInstance } from "element-plus"
import { parseSearchDate } from "@/common/utils/datetime"
import { deleteModelBatch, getModelSearch, searchClassifyApi } from "@@/apis/component"
import Card from "@@/components/CardItem/card.vue"
import { usePagination } from "@@/composables/usePagination"
import { Refresh, Search } from "@element-plus/icons-vue"
import XEUtils from "xe-utils"
import { useAutoRefresh } from "@/layouts/composables/useAutoRefresh";
import { isEmpty } from "lodash";
import TabSelectedScroll from "@@/components/TabSelectedScroll/index.vue"
import { isJSON } from "@/common/utils/parseParamValue"

defineOptions({
  // 命名当前组件
  name: "ComponentIndex"
})

const router = useRouter()
const isGrid = ref<boolean>(true)
const searchMore = ref<boolean>(false)
const searchFormRef = ref<FormInstance | null>(null)
const searchKey = ref()
const loading = ref<boolean>(false)
const tableData = ref<ModelData[]>([])
const multipleSelection = ref<ModelData[]>([])
const TableRef = ref()
// 获取标签
const tabData = ref<Record<string, number>>({})
const activeTab = ref("全部")
const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()

function handleBaseData() {
  router.replace({ name: "BasicDataIndex" })
}

function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}
function handleSearchMore() {
  searchMore.value = !searchMore.value
  if (!searchMore.value) {
    resetSearch()
  }
}
const searchData = reactive<ModelSearchData>({
  name: undefined,
  code: undefined,
  create_time: undefined,
  end_time: undefined,
  time_range: undefined,
  current_page: 0,
  tags: []
})
function buildSearchParams() {
  const params: ModelSearchData = {
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    code: undefined,
    name: undefined,
    tags: searchData.tags,
    create_time: undefined,
    end_time: undefined,
    searchKey: undefined
  }
  if (!searchMore.value) {
    params.searchKey = searchKey.value
  } else {
    params.name = searchData.name
    params.code = searchData.code
    if (searchData.time_range && searchData.time_range.length == 2) {
      params.create_time = searchData.time_range[0]
      params.end_time = parseSearchDate(searchData.time_range[1])
    }
  }
  return params
}
function getTableData() {
  loading.value = true
  const params = buildSearchParams()
  getModelSearch(params)
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
function handleSearch() {
  searchData.tags = ["全部"]
  searchAndClassify()
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
function searchAndClassify() {
  const params = buildSearchParams()
  searchClassifyApi(params).then((res: any) => {
    tabData.value = res.data
    activeTab.value = "全部"
  })
}
function handleRowCurrentChange(val: ModelData | undefined) {
  if (val == undefined) {

  }
}
function handleSelectionChange(val: ModelData[]) {
  multipleSelection.value = val
}
function handleMultipleDelete() {
  const ids: string[] = []
  const names: string[] = []
  multipleSelection.value.forEach((item) => {
    ids.push(item.id as string)
    names.push(item.name)
  })
  ElMessageBox.confirm(`正在删除组件模型：${names.join("，")}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteModelBatch(ids).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
function hanldeClearSelection() {
  nextTick(() => {
    TableRef.value.clearSelection()
  })
}
function getRowKeys(row: ModelData) {
  return row.id
}

// #region 删
function handleDelete(row: ModelData) {
  ElMessageBox.confirm(`正在删除组件模型：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    row.id
    && deleteModelBatch([row.id]).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
// #endregion
// #region 详情
function handleView(row: ModelData) {
  router.replace({ name: "ComponentView", query: { id: row.id } })
}
// #endregion

function handleToggleSelect(row: ModelData) {
  TableRef.value!.toggleRowSelection(row, undefined, false)
}
// 新建组件模型
function handleCreateTask() {
  router.replace({ name: "ComponentCreate" })
}

function searchByTags() {
  getTableData();
  searchAndClassify()
}

useAutoRefresh(() => {
  getTableData();
  searchAndClassify()
})

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

const selectedId = computed(() => {
  if (multipleSelection.value !== undefined && multipleSelection.value.length > 0) {
    const ids = XEUtils.map(multipleSelection.value, (item) => {
      return item.id
    })
    return ids
  }
  return []
})

function cardTag(item: ModelData) {
  if (isEmpty(item.tag) || (Array.isArray(item.tag) && JSON.parse(item.tag).length < 1)) {
    return "其他模型"
  }
  if (!isJSON(item.tag)) {
    return item.tag.split(",")[0]
  }
  return JSON.parse(item.tag)[0]
}
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-input v-model="searchKey" size="large" placeholder="请输入搜索内容" @keydown.enter="handleSearch" class="csc-search-input">
          <template #append>
            <el-button :icon="Search" v-throttle="() => handleSearch()" />
          </template>
        </el-input>
        <div class="csc-more" @click="handleSearchMore">
          <span>更多</span>
          <el-icon v-if="!searchMore">
            <ArrowDown />
          </el-icon>
          <el-icon v-else>
            <ArrowUp />
          </el-icon>
        </div>
      </div>
      <div class="cc-search-common-more" v-if="searchMore">
        <el-form ref="searchFormRef" :model="searchData" :inline="true">
          <el-form-item prop="code" label="名称">
            <el-input v-model="searchData.code" @change="handleSearch()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="name" label="别名">
            <el-input v-model="searchData.name" @change="handleSearch()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="time_range" label="时间范围">
            <el-date-picker
              v-model="searchData.time_range" type="daterange" unlink-panels range-separator="至"
              value-format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间" @change="handleSearch()"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="loading" class="content-other">
      <div class="mb-main-padding toolbar">
        <div class="flex-y-center tag">
          <el-button type="primary" @click="handleCreateTask">
            新建组件
          </el-button>
          <el-button type="primary" @click="handleBaseData">
            基础数据
          </el-button>
          <el-button
            :disabled="multipleSelection.length < 1" type="danger"
            @click="handleMultipleDelete"
          >
            批量删除
          </el-button>
        </div>
        <div class="flex-y-center sh-operate">
          <div class="tab">
            <TabSelectedScroll v-model:selecteds="searchData.tags" :data="tabData" @change="searchByTags" />
          </div>
          <div class="sh-btn" :class="{ active: isGrid }" @click="() => isGrid = true">
            <el-tooltip content="卡片" placement="bottom">
              <SvgIcon name="table-grid" />
            </el-tooltip>
          </div>
          <div class="sh-btn" :class="{ active: !isGrid }" @click="() => isGrid = false">
            <el-tooltip content="列表" placement="bottom">
              <SvgIcon name="table-list" />
            </el-tooltip>
          </div>
        </div>
      </div>
      <div v-show="isGrid" class="cpi-content-main">
        <div class="custom-card-container">
          <template v-for="(item, index) in tableData" :key="index">
            <Card
              :tag="cardTag(item)"
              :is-other="true"
              :name="item.code"
              :create-by="item.name"
              :create-time="item.updateTime == null ? '' : item.updateTime"
              :description="item.description == null ? '' : item.description"
              :data="item"
              :is-download="false"
              :selected="selectedId.includes(item.id as string)"
              :other-params="{
                createTime: item.createTime,
              }"
              @handle-delete="handleDelete"
              @handle-view="handleView"
              @toggle-select="handleToggleSelect"
            />
          </template>
        </div>
      </div>
      <div v-show="!isGrid" class="cpi-content-main">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table
              ref="TableRef" v-loading="loading" :data="tableData" :row-key="getRowKeys" :width="width"
              :height="height" @current-change="handleRowCurrentChange" @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" header-align="left" :reserve-selection="true" width="55" />
              <el-table-column prop="code" label="名称" header-align="left" max-width="350" />
              <el-table-column prop="name" show-overflow-tooltip label="别名" header-align="left" />
              <el-table-column prop="description" show-overflow-tooltip label="描述" header-align="left" />
              <el-table-column prop="updateTime" label="修改时间" header-align="left" width="180" />
              <el-table-column fixed="right" label="操作" align="center" width="140">
                <template #default="scope">
                  <el-space :size="12">
                    <el-link :underline="false" @click.stop v-throttle="() => handleView(scope.row)" title="查看">
                      <el-icon :size="18">
                        <View />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" type="danger" @click.stop v-throttle="() => handleDelete(scope.row)" title="删除">
                      <el-icon :size="18">
                        <Delete />
                      </el-icon>
                    </el-link>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-auto-resizer>
      </div>
    </div>
    <div class="pager-wrapper">
      <el-pagination
        background
        layout="total, sizes, ->, prev, pager, next, jumper"
        :disabled="loading"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :current-page="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/main-page.scss";
@import "@@/assets/styles/mixins.scss";

.toolbar {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.sh-operate {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  overflow: hidden;
  .tab {
    flex: 1;
    overflow: hidden;
    display: flex;
    justify-content: flex-end;
  }
}

@media screen and (max-width: 768px) {
  .toolbar {
    flex-direction: column;
  }
  .sh-operate {
    width: 100%;
  }
}
</style>
